package com.softstao.guoyu.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;

import com.softstao.guoyu.R;
import com.softstao.guoyu.accept.Accept;
import com.softstao.guoyu.accept.AcceptType;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.base.BaseFragment;
import com.softstao.guoyu.global.AppManager;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.DirectlyList;
import com.softstao.guoyu.model.me.MessageCount;
import com.softstao.guoyu.mvp.events.ActionEvent;
import com.softstao.guoyu.mvp.events.NotifyEvent;
import com.softstao.guoyu.mvp.interactor.IsCompleteInteractor;
import com.softstao.guoyu.mvp.interactor.me.MessageInteractor;
import com.softstao.guoyu.mvp.presenter.IsCompletePresenter;
import com.softstao.guoyu.mvp.presenter.me.MessagePresenter;
import com.softstao.guoyu.mvp.rxbus.RxBus;
import com.softstao.guoyu.mvp.viewer.IsCompleteViewer;
import com.softstao.guoyu.mvp.viewer.me.MessageViewer;
import com.softstao.guoyu.ui.activity.me.MyAuditActivity;
import com.softstao.guoyu.ui.activity.me.UserInfoActivity;
import com.softstao.guoyu.ui.fragment.AgentFragment;
import com.softstao.guoyu.ui.fragment.DiscoveryFragment;
import com.softstao.guoyu.ui.fragment.MeFragment;
import com.softstao.guoyu.ui.fragment.SaleFragment;
import com.softstao.guoyu.ui.fragment.ShopFragment;
import com.softstao.guoyu.widget.HintDialog;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.softstao.softstaolibrary.library.widget.NonSwipeableViewPager;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseActivity implements IsCompleteViewer,MessageViewer{

    @AIPresenter(presenter = IsCompletePresenter.class, interactor = IsCompleteInteractor.class)
    IsCompletePresenter presenter;
    @AIPresenter(presenter = MessagePresenter.class,interactor = MessageInteractor.class)
    MessagePresenter messagePresenter;

    @BindView(R.id.viewPager)
    NonSwipeableViewPager viewPager;
    @BindView(R.id.shop_radio)
    RadioButton shopRadio;
    @BindView(R.id.agent_radio)
    RadioButton agentRadio;
    @BindView(R.id.discovery_radio)
    RadioButton discoveryRadio;
    @BindView(R.id.sale_radio)
    RadioButton saleRadio;
    @BindView(R.id.me_radio)
    RadioButton meRadio;
    private ShopFragment shopFragment;
    private AgentFragment agentFragment;
    private DiscoveryFragment discoveryFragment;
    private SaleFragment saleFragment;
    private MeFragment meFragment;
    private RadioButton[] radioButtons = new RadioButton[5];
    private long waitTime = 2000;
    private long touchTime = 0;
    int currentIndex = 0;
    int selectedIndex;
    private List<BaseFragment> fragmentList = new ArrayList<>();

    @Override
    public int _ContentView() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        initData();
        radioButtons[0] = shopRadio;
        radioButtons[1] = agentRadio;
        radioButtons[2] = discoveryRadio;
        radioButtons[3] = saleRadio;
        radioButtons[4] = meRadio;
        initListener();
        shopFragment = new ShopFragment();
        agentFragment = new AgentFragment();
        discoveryFragment = new DiscoveryFragment();
        saleFragment = new SaleFragment();
        meFragment = new MeFragment();
        fragmentList.add(shopFragment);
        fragmentList.add(agentFragment);
        fragmentList.add(discoveryFragment);
        fragmentList.add(saleFragment);
        fragmentList.add(meFragment);
        viewPager.setOffscreenPageLimit(5);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }
        });
        radioButtons[currentIndex].setSelected(true);
        if (getIntent().getStringExtra("index") != null) {
            radioButtons[currentIndex].setSelected(false);
            currentIndex = Integer.parseInt(getIntent().getStringExtra("index"));
            if (currentIndex >= 2) {
                radioButtons[currentIndex].setSelected(true);
            }
            viewPager.setCurrentItem(currentIndex, false);
        } else {
            viewPager.setCurrentItem(0, false);
            radioButtons[0].setSelected(true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isComplete();
        findMessage();
    }

    private void initListener() {
        MyListener myButtonListener = new MyListener();
        for (int i = 0; i < radioButtons.length; i++) {
            radioButtons[i].setOnClickListener(myButtonListener);
        }
    }

    @Override
    public void isComplete() {
        presenter.isComplete(SharePreferenceManager.getInstance().getAgentId());
    }

    @Override
    public void isResult(DirectlyList directlyList) {
        SharePreferenceManager.getInstance().setDirectlyList(directlyList);
    }

    @Override
    public void findMessage() {
        messagePresenter.getMessageCount(SharePreferenceManager.getInstance().getAgentId());
    }

    @Override
    public void getMessageCount(MessageCount messageCount) {
        NotifyEvent notifyEvent = new NotifyEvent();
        notifyEvent.setNotify(messageCount.getCount());
        notifyEvent.setCart_notify(messageCount.getScount());
        notifyEvent.setFromOrderCount(messageCount.getFromOrderCount());
        notifyEvent.setToOrderCount(messageCount.getToOrderCount());
        notifyEvent.setTransferOrderCount(messageCount.getTransferOrderCount());
        RxBus.get().post(notifyEvent);
    }

    public boolean Complete(){
        try {
            if (SharePreferenceManager.getInstance().getDirectlyList().getIsCompleteInfo()==0){
                showInfo();
                return false;
            }else {
                if (SharePreferenceManager.getInstance().getDirectlyList().getIsAudit()==0){
                    showAudit();
                    return false;
                }
            }
        }catch (NullPointerException e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void showAudit(){
        HintDialog dialog = new HintDialog(context,R.style.MyDialog);
        dialog.getWindow().setLayout(getScreenWidth()- LZUtils.dipToPix(context,55)*2, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setIcon(R.mipmap.hint_icon_alert);
        dialog.setTitle("未授权暂不开放此功能");
        dialog.setContentVisible();
        dialog.setContent("若想使用该功能，请立刻申请授权");
        dialog.setConfirm("去申请授权");
        dialog.getConfirm().setOnClickListener(v -> {
            dialog.dismiss();
            startActivity(new Intent(context,MyAuditActivity.class));
        });
        dialog.show();
    }

    public void showInfo(){
        HintDialog dialog = new HintDialog(context,R.style.MyDialog);
        dialog.getWindow().setLayout(getScreenWidth()- LZUtils.dipToPix(context,55)*2, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setIcon(R.mipmap.hint_icon_alert);
        dialog.setTitle("资料未完善");
        dialog.setContentVisible();
        dialog.setContent("请完善资料，尽早获得授权！");
        dialog.setConfirm("去完善资料");
        dialog.getConfirm().setOnClickListener(v -> {
            dialog.dismiss();
            startActivity(new Intent(context,UserInfoActivity.class));
        });
        dialog.show();
    }

    class MyListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.shop_radio:
                    selectedIndex = 0;
                    break;
                case R.id.agent_radio:
                    selectedIndex = 1;
                    if (!Complete()){
                        return;
                    }
                    break;
                case R.id.discovery_radio:
                    selectedIndex = 2;
                    LZToast.getInstance(context).showToast("程序猿正在加班中...");
                    break;
                case R.id.sale_radio:
                    selectedIndex = 3;
                    if (!Complete()){
                        return;
                    }
                    break;
                case R.id.me_radio:
                    selectedIndex = 4;
                    break;
            }
            if (selectedIndex != currentIndex) {
                if (selectedIndex!=2) {
                    viewPager.setCurrentItem(selectedIndex);
                }
                radioButtons[currentIndex].setSelected(false);
                radioButtons[selectedIndex].setSelected(true);
                currentIndex = selectedIndex;
            }
        }
    }

    @Accept({
            @AcceptType(tag = ActionEvent.SET_COLOR, clazz = int.class)
    })
    public void onPostAccept(Object tag, Object event) {
        if ((int) event == 100) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    tintManager.setStatusBarTintColor(Color.TRANSPARENT);
                }
            }, 200);
        } else if ((int) event == 102) {
            tintManager.setStatusBarTintColor(Color.TRANSPARENT);
        } else {
            tintManager.setStatusBarTintColor(getResources().getColor(R.color.colorPrimary));
        }
    }

    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if ((currentTime - touchTime) >= waitTime) {
            LZToast.getInstance(this).showToast("再按一次退出" + getResources().getString(R.string.app_name));
            touchTime = currentTime;
        } else {
            AppManager.getAppManager().AppExit();
        }
    }

    private void initData(){

//        //设置主题
//        //ThemeConfig.CYAN
//        ThemeConfig theme = new ThemeConfig.Builder()
//                .setTitleBarTextColor(this.getResources().getColor(R.color.font_black))
//                .setTitleBarBgColor(Color.WHITE)
//                .setTitleBarIconColor(this.getResources().getColor(R.color.theme_color))
//                .setCheckNornalColor(Color.GRAY)
//                .setCheckSelectedColor(this.getResources().getColor(R.color.theme_color))
//                .setIconCamera(R.mipmap.camera)
//                .setIconBack(R.mipmap.back)
//                .build();
//        //配置功能
//        FunctionConfig functionConfig = new FunctionConfig.Builder()
//                .setEnableCamera(true)
//                .setEnableEdit(true)
//                .setEnableCrop(true)
//                .setEnableRotate(true)
//                .setCropSquare(true)
//                .setEnablePreview(true)
//                .build();
//
//        //配置imageloader
//        ImageLoader imageloader = new GlideImageLoader();
//        CoreConfig coreConfig = new CoreConfig.Builder(getApplicationContext(), imageloader, theme)
//                .setFunctionConfig(functionConfig)
//                .setNoAnimcation(true)
//                .build();
//        GalleryFinal.init(coreConfig);
    }
}
